﻿using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Http;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Wangu.Sync.Service.PlugIn
{

    public class ResultMessage
    {
        public int code { get; set; }
        public Object data { get; set; }
        public string msg { get; set; }
    }

    /// <summary>
    /// 【服务插件】AfterExecuteOperationTransaction
    /// </summary>
    [Description("【同步数据到第三方系统服务插件】AfterExecuteOperationTransaction"), HotUpdate]
    public class SyncServicePlugIn : AbstractOperationServicePlugIn
    {
        private static readonly HttpClient _httpClient = new HttpClient();

        public static async Task<string> PostJsonAsync(string url, string data)
        {
            var content = new StringContent(data, Encoding.UTF8, "application/json");
            var response = await _httpClient.PostAsync(url, content);
            response.EnsureSuccessStatusCode();
            return await response.Content.ReadAsStringAsync();
        }

        /// <summary>
        /// KEY类
        /// </summary>
        internal static class KeyConst
        {
            public static string AreaKey = "Wangu";
            public static string RegionKey = "Wangu:Sync";
            public static string CacheKey = "SendBillDataList:{0}";

            public static string Url = "http://127.0.0.1:48080/admin-api/sync/k3cloud/bill-data";
            public static Dictionary<string, string> Header = new Dictionary<string, string>() {
                    { "Content-Type", "application/json" }
                };
        }

        /// <summary>
        /// 清理缓存
        /// </summary>
        public void ClearCache()
        {
            CacheUtil.SetCache(this.Context.GetAreaCacheKey(), KeyConst.RegionKey, KeyConst.CacheKey, new HashSet<List<string>>());
        }

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="data"></param>
        public void SetCache(string key, HashSet<List<string>> data)
        {
            CacheUtil.SetCache(this.Context.GetAreaCacheKey(), KeyConst.RegionKey, KeyConst.CacheKey, data);
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <returns></returns>
        public object GetCache()
        {
            return CacheUtil.GetCache(this.Context.GetAreaCacheKey(), KeyConst.RegionKey, KeyConst.CacheKey);
        }

        public override void AfterExecuteOperationTransaction(AfterExecuteOperationTransaction e)
        {
            base.AfterExecuteOperationTransaction(e);
            DynamicObject[] dataEntities = e.DataEntitys;//数据包集合
            OperateResultCollection oResult = this.OperationResult.OperateResult;//抓取当前单据操作结果集
            bool IsSuccess = this.OperationResult.IsSuccess;
            if (IsSuccess && oResult.Count > 0)
            {
                PushBill(dataEntities);
            }
        }

        public HashSet<List<string>> CacheAddOrUpdate(string key, List<string> billData)
        {
            HashSet<List<string>> cacheList = GetCache() as HashSet<List<string>> ?? new HashSet<List<string>>();
            cacheList.Add(billData);
            SetCache(key, cacheList);
            return cacheList;
        }

        /// <summary>
        /// 数据处理
        /// </summary>
        /// <param name="dataEntities"></param>
        public void PushBill(DynamicObject[] dataEntities)
        {
            string AreaKey = this.Context.GetAreaCacheKey();
            string dbKey = this.Context.GetDBCacheKey();
            string orgNumber = this.Context.CurrentOrganizationInfo.ID.ToString();

            // http请求
            string idValue = dataEntities[0]["Id"].ToString();  // 主键
            string numberValue = ObjectUtils.Object2String(
                this.BusinessInfo.GetBillNoField().DynamicProperty.GetValueFast(dataEntities[0])); // 单据号
            string formId = this.BusinessInfo.GetForm().Id;
            List<string> billData = new List<string>() { formId, idValue, numberValue };

            string key = String.Format(KeyConst.CacheKey, formId);
            HashSet<List<string>> dataList = CacheAddOrUpdate(key, billData);

            SendData(key, dataList);

        }

        /// <summary>
        /// 异步http请求
        /// </summary>
        /// <param name="data"></param>
        public async Task SendData(string key, HashSet<List<string>> data) 
        {
            try
            {
                string jsonData = JsonUtil.Serialize(data);
                string response = await PostJsonAsync(KeyConst.Url, jsonData);
                //string response = HttpUtil.PostJson(KeyConst.Url, 5000, jsonData);
                var rtn = JsonUtil.DeserializeObject<ResultMessage>(response);
                if (rtn.code != 0)
                {
                    // 清理记录

                } else
                {
                    // 新增记录

                }

            }
            catch (Exception ex)
            {
                Console.WriteLine($"请求异常：{ex.Message}");
            }
        }

    }
}
